import 'dart:async';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_demo/http/api.dart';
import 'package:flutter_demo/other/application.dart';
import 'package:flutter_demo/widget/buttons.dart';
import 'package:flutter_demo/widget/search.dart';
import 'package:flutter_demo/widget/tiny_widgets.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:universal_html/html.dart' as html;

class SearchApplyScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _SearchApplyScreenState();
}

class _SearchApplyScreenState extends State<SearchApplyScreen> {

  late String lastSearch;
  bool isNonSearch = true;

  late Future<List> searchFuture;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(
            width: double.infinity,
            height: 60,
            padding: EdgeInsets.symmetric(
              horizontal: 195,
            ),
            decoration: BoxDecoration(
              color: Color(0xff1a56a8),
            ),
            child: Container(
              width: 580,
              height: 59,
              alignment: Alignment.centerLeft,
              child: Image(
                image: NetworkImage('http://my.gxrczc.com/assets/img/logo_zc.png'),
              ),
            ),
          ),
          Container(
            decoration: BoxDecoration(
              color: Color(0xff1a56a8),
            ),
            padding: EdgeInsets.only(
              top: 8,
              left: 32,
              right: 32,
              bottom: 16,
            ),
            child: SearchWidget(
              hintText: '请输入单位名称进行搜索',
              onSearchCallback: (content) => setState(() {
                if (isNonSearch) isNonSearch = false;
                lastSearch = content;
              }),
            ),
          ),
          Expanded(
            child: Container(
              width: double.infinity,
              height: double.infinity,
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(
                vertical: 16,
                horizontal: 64,
              ),
              decoration: BoxDecoration(
                color: Colors.white,
              ),
              child: isNonSearch
              ? Center(
                child: Text(
                  '暂无记录',
                  style: TextStyle(
                    fontSize: 20,
                    color: Colors.black87,
                  ),
                ),
              )
              : FutureBuilder<List>(
                future: doSearch(),
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.done) {
                    if (snapshot.hasError) {
                      return Center(
                        child: Text(
                          '${snapshot.error}',
                          style: TextStyle(
                            fontSize: 20,
                            color: Colors.black87,
                          ),
                        ),
                      );
                    } else if (snapshot.data!.isEmpty) {
                      return Center(
                        child: Text(
                          '暂无记录',
                          style: TextStyle(
                            fontSize: 20,
                            color: Colors.black87,
                          ),
                        ),
                      );
                    } else {
                      return ListView(
                        children: [
                          for (int i = 0; i < snapshot.data!.length; i++) ...[
                            content(context, snapshot.data![i]),
                            C(16),
                          ]
                        ],
                      );
                    }
                  } else {
                    return Center(child: CircularProgressIndicator());
                  }
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget content(BuildContext context, dynamic map) {
    return Container(
      padding: EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Color(0xffe4f0ff),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: double.infinity,
            height: 130,
            alignment: Alignment.topLeft,
            child: Wrap(
              direction: Axis.vertical,
              spacing: 10,
              runSpacing: 74,
              children: map.entries.map<Widget>((entry) {
                var value = entry.value;
                if (entry.key.contains('申报日期')) {
                  var date = DateTime.fromMillisecondsSinceEpoch(int.parse(entry.value));
                  value = '${date.year}年${date.month}月${date.day}日';
                }
                return item(context, entry.key, value);
              }).toList(),
            ),
          ),
          if (map['审核状态'].toString().contains('单位审核'))
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                BaseButton(
                  radius: 4,
                  width: 70,
                  height: 36,
                  withShadow: false,
                  centerButton: false,
                  buttonColor: Colors.green,
                  onTap: () => submmitApply(int.parse(map['审核序号']), '通过'),
                  child: Text(
                    '通过',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 14,
                    ),
                  ),
                ),
                C(8),
                BaseButton(
                  radius: 4,
                  width: 70,
                  height: 36,
                  withShadow: false,
                  centerButton: false,
                  buttonColor: Colors.red,
                  onTap: () => submmitApply(map['id'], '不通过'),
                  child: Text(
                    '不通过',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 14,
                    ),
                  ),
                ),
              ],
            ),
        ],
      ),
    );
  }

  Widget item(BuildContext context, String title, dynamic data) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          child: Text(
            '$title :',
            style: TextStyle(
              color: Color(0xff333333),
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        C(8),
        Container(
          child: title.contains('申报附件')
          ? InkWell(
            onTap: () => downloadFile(title, data),
            child: Text(
              '点击下载$title',
              style: TextStyle(
                color: Colors.blue,
                fontSize: 16,
              ),
            ),
          )
          : Text(
            data == null ? '' : data.toString(),
            style: TextStyle(
              color: Color(0xff333333),
              fontSize: 16,
            ),
          ),
        ),
      ],
    );
  }

  void downloadFile(String title, String data) {
    final anchor = html.document.createElement('a') as html.AnchorElement
      ..href = SystemApi.downloadUrl + data
      ..style.display = 'none'
      ..download = '$title.${data.split('.').last}';
    html.document.body!.children.add(anchor);
    anchor.click();
  }

  Future<List> doSearch() async {
    Response response = await SystemApi.search_apply(lastSearch);
    if (response.statusCode == 200) {
      return json.decode(response.data);
    } else {
      Fluttertoast.showToast(msg: response.statusCode.toString());
      return Future.error('状态码: ${response.statusCode.toString()}');
    }
  }

  Future<void> submmitApply(int id, String companyResult) async {
    Future.wait([
      SystemApi.c_submmit_apply(id, companyResult),
      SystemApi.r_submmit_apply(id, companyResult)
    ]).then((results) {
      bool allSuccess = false;
      for (int i = 0; i < results.length; i++) {
        var map = json.decode(results[i].data);
        if (results[i].statusCode == 200 && map['code'] == '1') {
          allSuccess = true;
          Fluttertoast.showToast(msg: map['msg']);
        } else if (map['code'] != '1') {
          Fluttertoast.showToast(msg: map['msg']);
        } else {
          allSuccess = false;
          Fluttertoast.showToast(msg: results[i].statusCode.toString());
        }
      }
      if (allSuccess) setState(() {});
    });
  }
}